// pages/cart/cart.js
import { request } from "../../request/request"
Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {

  },
  onShow: function () {
    let address = wx.getStorageSync('address');
    let cart = wx.getStorageSync('cart') || [];
    cart = cart.filter(v => v.checked);
    this.setCart(cart);
    this.setData({
      address
    })
  },
  // 支付
  handlePay() {
    // 1 判断缓存中是否有token，如果没有就跳转到授权页面获取token
    const { token } = wx.getStorageSync('token');
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/auth',
      })
    }
    // 3 创建订单
    // 3.1 准备请求头 参数
    const header = { Authorization: token };
    // 3.2 准备请求 体参数
    const order_price = this.data.totalPrice; // 价格
    const consignee_addr = this.data.address.all; // 地址
    const cart = this.data.cart; // 商品数组
    let goods = [];
    cart.forEach(v => goods.push({
      goods_id: v.goods_id,
      goods_number: v.num,
      goods_price: v.goods_price
    }))
    const orderParams = { order_price, consignee_addr, goods };
    // 4 发送请求 创建订单 获取订单号
     const {goods_number} =  request({ url: "/my/orders/create", method: "post", data: orderParams, header: header })
    // 5 发起预支付请求
    const {res} = request({url:"my/orders/chkOrder",method: "post",header: header,data:{goods_number}})
    // 6 发起微信支付 并 把 pay 的传进去
    // wx.requestPayment({
    //   nonceStr,
    //   package,
    //   paySign,
    //   timeStamp,
    // })
    // 7 查询后台 订单的状态
    const succes = request({url:"my/orders/chkOrder",method: "post",header: header,data:{goods_number}}) // 支付成功
    wx.showToast({
      title: '支付成功',
    })
    wx.navigateTo({
      url: '/page/order/order',
    })

  },
  // 设置
  setCart(cart) {
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.goods_price * v.num;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    })
    this.setData({
      cart,
      totalPrice,
      totalNum
    })
  }
})